<template>
  <!-- 搜索区域 -->
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="配置键">
        <el-input v-model="pageRequest.model.type" placeholder="请输入配置键"></el-input>
      </el-form-item>
      <el-form-item label="配置描述">
        <el-input v-model="pageRequest.model.description" placeholder="请输入配置描述"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 数据表格区域 -->
  <el-card style="margin: 10px 0;">
    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
    <el-table
        style="margin: 10px 0;"
        v-loading="loading"
        :data="tableData"
        border
    >
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="type" label="配置键" min-width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="配置描述" min-width="120" show-overflow-tooltip></el-table-column>
      <el-table-column
          prop="config"
          label="用户配置"
          min-width="120"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="config" label="系统预制" width="80" align="center" show-overflow-tooltip>
        <template #default="{row}">
          <el-tag v-if="row.system">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260" align="center" fixed="right">
        <template #default="{row}">
          <el-button size="small" type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" v-if="!row.system"  icon="Delete" @click="deleteConfig(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="pageParams.pageNum"
        v-model:page-size="pageParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
    ></el-pagination>
  </el-card>

  <!-- 新增/编辑对话框 -->
  <el-drawer
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="配置描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入配置描述"></el-input>
      </el-form-item>
      <el-form-item label="配置键" prop="type">
        <el-input :disabled="isEdit" v-model="formData.type" placeholder="请输入配置键"></el-input>
      </el-form-item>
      <el-form-item label="配置值" prop="config">
        <el-input v-model="formData.config" type="textarea" :rows="4" placeholder="请输入配置值"></el-input>
      </el-form-item>
      <el-form-item v-show="!isEdit">
        <el-alert type="warning">
          注意：新增的值不是“系统预制”值！
        </el-alert>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="js">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getConfigPage,
  addConfig,
  updateConfig,
  deleteConfigs
} from '@/api/system/config'

let pageRequest = ref({
  page: {
    index: 1,
    size: 10,
  },
  model: {
    description: '',
    type: '',
  }
});

// 表格数据
const tableData = ref([])
const loading = ref(false)    // 加载状态
const total = ref(0)          // 总条数

// 分页参数
const pageParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 表单数据和校验规则
const formRef = ref()
const formData = reactive({
  description: '',
  type: '',
  config: ''
})
const formRules = reactive({
  description: [{ required: true, message: '请输入配置描述', trigger: 'blur' }],
  type: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
  config: [{ required: true, message: '请输入配置值', trigger: 'blur' }]
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)  // 是否为编辑模式


/**
 * 获取配置数据
 */
const fetchData = async () => {
  try {
    loading.value = true
    const res = await getConfigPage(pageRequest.value)
    tableData.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索配置
 */
const handleSearch = () => {
  pageRequest.value.page.index = 1
  fetchData()
}

/**
 * 重置搜索条件
 */
const resetSearch = () => {
  pageRequest.value.model.description = ''
  pageRequest.value.model.type = ''
  handleSearch()
}

/**
 * 新增配置
 */
const handleAdd = () => {
  dialogTitle.value = '新增配置'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

/**
 * 编辑配置
 * @param row 配置项数据
 */
const handleEdit = (row) => {
  dialogTitle.value = '编辑配置'
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.id = null
  formData.description = ''
  formData.type = ''
  formData.config = ''
  formRef.value?.resetFields()
}

/**
 * 提交表单
 */
const submitForm = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    if (isEdit.value) {
      // 编辑配置
      await updateConfig(formData)
      ElMessage.success('更新成功')
    } else {
      // 新增配置
      const _formData = {
        ...formData,
        system: 0,  // 新增的配置默认不是系统预制
        status: 1
      }
      await addConfig(_formData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    fetchData()  // 刷新数据
  } catch (error) {
    console.error('表单提交失败:', error)
  }
}

const deleteConfig = async (id) => {
  try {
    await deleteConfigs(id)
    ElMessage.success('删除成功')
    tableData.value = tableData.value.filter(item => item.id !== id)
  } catch (error) {
    ElMessage.error('删除配置失败')
  }
}

/**
 * 每页条数变化
 * @param size 新的每页条数
 */
const handleSizeChange = (size) => {
  pageParams.pageSize = size
  fetchData()
}

/**
 * 当前页码变化
 * @param page 新的页码
 */
const handlePageChange = (page) => {
  pageParams.pageNum = page
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.form {
  margin-top: 15px;
  display: flex;
  align-items: center;
}
</style>
